package com.yuedou.jylt.constant;

import android.app.Application;
import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.xuexiang.xupdate.XUpdate;
import com.xuexiang.xupdate.entity.UpdateError;
import com.xuexiang.xupdate.listener.OnUpdateFailureListener;
import com.xuexiang.xupdate.logs.ILogger;
import com.xuexiang.xupdate.utils.UpdateUtils;
import com.yuedou.jylt.bean.DeviceMaterialBean;
import com.yuedou.jylt.dto.DeviceMaterialObj;
import com.yuedou.jylt.dto.ResponseObj;
import com.yuedou.jylt.dto.param.DeviceMaterialParam;
import com.yuedou.jylt.dto.param.InitDeviceParam;
import com.yuedou.jylt.http.OKHttpUpdateHttpService;
import com.yuedou.jylt.http.RequestServices;
import com.yuedou.jylt.http.RequestUtils;
import com.yuedou.jylt.sharedpref.SharedPref;
import com.yuedou.jylt.sharedpref.SharedPrefConstant;
import com.yuedou.jylt.utils.CPUUtil;
import com.yuedou.jylt.utils.DirectoryUtils;
import com.yuedou.jylt.utils.MyOnInstallListener;

import java.io.File;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.List;

import androidx.annotation.NonNull;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * @ClassName: MApplication
 * @Description: 全局变量
 * @author mr.zhou
 * @date 2013-11-26 下午1:32:44
 * 
 */
public class MApplication extends Application implements UncaughtExceptionHandler {

	public static MApplication mApplicationContext = null;
	public static SharedPref mSharedPref = null;
	public int screenWidth = 0;
	public int screenHeight = 0;

	private static final long SPLASH_DELAY_MILLIS = 1000;
	private static final int GO_HOME = 1000;

	//图片视频的缓存目录
	private File cache;

	private String macAddress = "";
	private String simSerialNumber = "";

	@Override
	public void onCreate() {
		super.onCreate();
//		System.out.println("Environment.DIRECTORY_DCIM : " + Environment.getDataDirectory().toString());
//		DirectoryUtils.getEnvironmentDirectories();

//        EventBus.getDefault().register(this);
		boolean bl = DirectoryUtils.isExistSdCard();
		System.out.println("是否存在sdcard: " + bl);
		//创建缓存目录，系统一运行就得创建缓存目录的，
		String destDir = Environment.getExternalStorageDirectory().toString() + "/material";
		System.out.println("destDir : " + destDir);
		cache = new File(Environment.getExternalStorageDirectory().toString(), "material");
		if(!cache.exists()){
			boolean blMk = cache.mkdirs();
			if(blMk){
				System.out.println("创建成功");
			}else{
				System.out.println("创建失败");
			}
		}


		File cache = new File(Environment.getExternalStorageDirectory().toString(), "appVersion");
		if(!cache.exists()){
			boolean blMk = cache.mkdirs();
			if(blMk){
				System.out.println("创建成功");
			}else{
				System.out.println("创建失败");
			}
		}

		mApplicationContext = this;
		// 获取电话管理者
		//获取系统的TelephonyManager对象
		TelephonyManager tManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		//获取sim卡序列号
		if(tManager!=null){
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//				System.out.println("imei = " + tManager.getImei());
			}
			System.out.println("SIM 卡编号：" + simSerialNumber);
		}
		//d32bc18cff33c1ce
		String decideId = CPUUtil.getDivicesNumbr(this);
		System.out.println("decideId：" + decideId);
		this.simSerialNumber = decideId;//tManager.getSimSerialNumber();

		mSharedPref = SharedPref.getInstance(SharedPrefConstant.PREF_NAME, this); // 单例sp
//		UnCeHandle unCatch = new UnCeHandle(this);
//		macAddress = "08E9F6ADD790";//CPUUtil.getMacAddress();
//		macAddress = CPUUtil.getMacAddress();
		macAddress = decideId;//Build.SERIAL;
		System.out.println("设备序列号 : " + macAddress);
		//getMacAddress ： 08:e9:f6:ad:d7:92
		System.out.println("macAddress ： " + macAddress);

		mSharedPref.putSharePrefString(SharedPrefConstant.DEVICE_SERIAL_NUM,macAddress);
		mSharedPref.putSharePrefInteger(SharedPrefConstant.DEVICE_ONLINE_STATE,0);
		mSharedPref.putSharePrefInteger(SharedPrefConstant.DEVICE_STATE,0);

		new Thread(new MyThread()).start();
		updateApp();
	}

	/**
	 * Handler:跳转到不同界面
	 */
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case GO_HOME:
					onHttpDeviceDetail(macAddress);
					break;
			}
			super.handleMessage(msg);
		}
	};

	public class MyThread implements Runnable {
		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				Thread.sleep(5000);// 线程暂停10秒，单位毫秒
				Message message = new Message();
				message.what = 1;
				message.obj = macAddress;
//					mHandler.sendMessage(message);// 发送消息
				mHandler.sendEmptyMessageDelayed(GO_HOME, SPLASH_DELAY_MILLIS);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}



	/**
	 *  获取设备详情的 网络请求
	 */
	private void onHttpDeviceDetail(String serialNumber){
		//步骤4:创建Retrofit对象
		RequestServices requestServices = RequestUtils.getRetrofit().create(RequestServices.class);
		//对 发送请求 进行封装
		InitDeviceParam deviceParam = new InitDeviceParam();
		deviceParam.setCpu_id(serialNumber);
		deviceParam.setSim_card_num(this.simSerialNumber);
		System.out.println("deviceParam: " +  deviceParam.toString());
		Call<ResponseObj> call = requestServices.robotDetail(deviceParam);
		//步骤6:发送网络请求(异步)
		call.enqueue(new Callback<ResponseObj>() {
			@Override
			public void onResponse(Call<ResponseObj> call, @NonNull Response<ResponseObj> response) {
				Log.i("获取初始化设备 返回数据",response.toString());
				ResponseObj responseObj = response.body();
				System.out.println("获取初始化设备 返回数据: " + response.body().toString());
				System.out.println("data: " + responseObj.getData().toString());
				System.out.println();
				if (responseObj != null) {
					// 成功
					int deviceId = responseObj.getData().containsKey("id")
							? Integer.parseInt(responseObj.getData().get("id").toString()) : 0;
//					String qrCode = responseObj.getData().get("qrCode").toString();
					String serialNum = responseObj.getData().get("serialNum").toString();
					int state = responseObj.getData().containsKey("state")
							? Integer.parseInt(responseObj.getData().get("state").toString()) : 0;
//					String version = responseObj.getData().get("version").toString();


					mSharedPref.putSharePrefInteger(SharedPrefConstant.DEVICE_ID,deviceId);
					mSharedPref.putSharePrefString(SharedPrefConstant.DEVICE_SN,serialNum);

//					mSharedPref.putSharePrefString(SharedPrefConstant.DEVICE_QRCODE,qrCode);
					mSharedPref.putSharePrefInteger(SharedPrefConstant.DEVICE_STATE,state);
//					mSharedPref.putSharePrefString(SharedPrefConstant.DEVICE_MATERIAL_VERSION,version);

					//创建缓存目录，系统一运行就得创建缓存目录的，
//					String destDir = Environment.getExternalStorageDirectory().toString() + "/material";
//					System.out.println("destDir : " + destDir);
//					File cache = new File(Environment.getExternalStorageDirectory().toString(), "material");
//					if(!cache.exists()){
//						boolean blMk = cache.mkdirs();
//						if(blMk){
//							System.out.println("创建成功");
//						}else{
//							System.out.println("创建失败");
//						}
//					}
				}
			}

			@Override
			public void onFailure(Call<ResponseObj> call, Throwable t) {
				t.printStackTrace();
				Log.d("获取设备信息详情 失败", t.getMessage());
			}
		});
	}


	/**
	 *  xUpdate 初始化操作
	 */
	private void updateApp(){
		String destDir = Environment.getExternalStorageDirectory().toString() + "/appVersion";
		File cache = new File(Environment.getExternalStorageDirectory().toString(), "appVersion");
		if(!cache.exists()){
			boolean blMk = cache.mkdirs();
			if(blMk){
				System.out.println("创建成功");
			}else{
				System.out.println("创建失败");
			}
		}

		XUpdate.get()
				.isWifiOnly(false)     //默认设置只在wifi下检查版本更新
				.isGet(true)          //默认设置使用get请求检查版本
				.isAutoMode(true)    //默认设置非自动模式，可根据具体使用配置
				.param("VersionCode", UpdateUtils.getVersionCode(this)) //设置默认公共请求参数
				.param("AppKey", getPackageName())
                .debug(true)
				.setOnInstallListener(new MyOnInstallListener())
				.setApkCacheDir(destDir)
				.setOnUpdateFailureListener(new OnUpdateFailureListener() { //设置版本更新出错的监听
					@Override
					public void onFailure(UpdateError error) {
//						Toast.makeText(error.toString());
						System.out.println("onFailure: " + error.toString());
					}
				}).setIUpdateHttpService(new OKHttpUpdateHttpService()) //这个必须设置！实现网络请求功能。
				.setILogger(new ILogger() {
					@Override
					public void log(int priority, String tag, String message, Throwable t) {
						//实现日志记录功能
						System.out.println("ILogger: "+ tag);
						System.out.println("ILogger: "+ message);
					}
				})
				.init(this);   //这个必须初始化
	}

	/**
	 *  获取 广告 网络请求
	 */
	private void onHttpDeviceMaterial(){
		int deviceId = MApplication.mSharedPref.getSharePrefInteger(SharedPrefConstant.DEVICE_ID);
		String deviceSn = MApplication.mSharedPref.getSharePrefString(SharedPrefConstant.DEVICE_MATERIAL);
		try{
			//步骤4:创建Retrofit对象
			RequestServices requestServices = RequestUtils.getRetrofit().create(RequestServices.class);
			//对 发送请求 进行封装
			DeviceMaterialParam materialParam = new DeviceMaterialParam();
			materialParam.setDevice_id(deviceId);
			Call<DeviceMaterialObj> call = requestServices.materialList(materialParam);
			//步骤6:发送网络请求(异步)
			call.enqueue(new Callback<DeviceMaterialObj>() {
				@Override
				public void onResponse(Call<DeviceMaterialObj> call, @NonNull Response<DeviceMaterialObj> response) {
					Log.i("获取 广告 返回数据",response.toString());
					DeviceMaterialObj materialObj = response.body();
					System.out.println("获取 广告 返回数据: " + materialObj.getData().toString());
					if (materialObj != null) {
						// 成功
						String version = materialObj.getData().getVersion();
						List<DeviceMaterialBean> materials = materialObj.getData().getMaterials();
						System.out.println("获取 广告 返回数据: " + version);
						System.out.println("获取 广告 返回数据: " + materials);

						for (DeviceMaterialBean matrailBean: materials){
							System.out.println("imgUrl:" + matrailBean.getImgUrl());
						}

						MApplication.mSharedPref.putSharePrefString(SharedPrefConstant.DEVICE_MATERIAL_VERSION,version);
						MApplication.mSharedPref.putSharePrefString(SharedPrefConstant.DEVICE_MATERIAL,deviceSn);
					}
				}

				@Override
				public void onFailure(Call<DeviceMaterialObj> call, Throwable t) {
					t.printStackTrace();
					Log.d("获取 广告 失败", t.getMessage());
				}
			});
		}catch (Exception e){
			e.printStackTrace();
		}
	}


	/**
	 * 清除用户状态信息
	 * <h1>不清除会导致登录用户状态错误</h1>
	 */
	public void clearSavedInfo(){
		MApplication.mSharedPref.clear();
	}

	@Override
	public void uncaughtException(Thread thread, Throwable ex) {
		android.os.Process.killProcess(android.os.Process.myPid());

	}

	public int getScreenWidth() {
		return screenWidth;
	}

	public void setScreenWidth(int screenWidth) {
		this.screenWidth = screenWidth;
	}

	public int getScreenHeight() {
		return screenHeight;
	}

	public void setScreenHeight(int screenHeight) {
		this.screenHeight = screenHeight;
	}
	
}
